#!/usr/bin/env python3
"""
OBS Studio HTTP API Server
提供HTTP POST接口控制OBS Studio视频播放
"""

import logging
from typing import Dict, Any, Optional
from flask import Flask, request, jsonify
from flask_cors import CORS

from src.obs_client import OBSClient
from src.video_controller import VideoController

app = Flask(__name__)
CORS(app)

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class OBSAPIController:
    """OBS API控制器"""
    
    def __init__(self):
        self.obs_client = None
        self.video_controller = None
        self.current_config = None
    
    def connect_obs(self, host: str, port: int, password: str) -> bool:
        """连接到OBS Studio"""
        try:
            # 如果已有连接且配置相同，复用连接
            if (self.obs_client and self.obs_client.is_connected() 
                and self.current_config 
                and self.current_config['host'] == host 
                and self.current_config['port'] == port 
                and self.current_config['password'] == password):
                return True
            
            # 断开旧连接
            if self.obs_client:
                self.obs_client.disconnect()
            
            # 创建新连接
            self.obs_client = OBSClient(host=host, port=port, password=password)
            if self.obs_client.connect():
                self.video_controller = VideoController(self.obs_client)
                self.current_config = {
                    'host': host,
                    'port': port,
                    'password': password
                }
                logger.info(f"成功连接到OBS: {host}:{port}")
                return True
            else:
                logger.error(f"连接OBS失败: {host}:{port}")
                return False
                
        except Exception as e:
            logger.error(f"连接OBS异常: {e}")
            return False
    
    def disconnect_obs(self):
        """断开OBS连接"""
        if self.obs_client:
            self.obs_client.disconnect()
            self.obs_client = None
            self.video_controller = None
            self.current_config = None


# 全局控制器实例
obs_controller = OBSAPIController()


@app.route('/api/obs/control', methods=['POST'])
def obs_control():
    """
    OBS控制接口
    
    请求参数:
    {
        "host": "localhost",
        "port": 4455,
        "password": "your_password",
        "default_scene": "场景名称",
        "preferred_media_sources": ["媒体源1", "媒体源2"],
        "command": "play|pause|resume|stop|show|hide|status|sources|switch",
        "source_name": "目标媒体源名称", // 某些命令需要
        "visible": true|false  // show/hide命令需要
    }
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": "请求数据为空"}), 400
        
        # 提取连接参数
        host = data.get('host', 'localhost')
        port = data.get('port', 4455)
        password = data.get('password', '')
        default_scene = data.get('default_scene')
        preferred_sources = data.get('preferred_media_sources', [])
        command = data.get('command')
        source_name = data.get('source_name')
        visible = data.get('visible', True)
        
        if not command:
            return jsonify({"error": "缺少command参数"}), 400
        
        # 连接到OBS
        if not obs_controller.connect_obs(host, port, password):
            return jsonify({"error": "无法连接到OBS Studio"}), 500
        
        # 处理场景切换
        if default_scene:
            if not obs_controller.obs_client.set_current_scene(default_scene):
                return jsonify({"error": f"切换场景失败: {default_scene}"}), 500
        
        # 获取当前场景
        current_scene = obs_controller.obs_client.get_current_scene()
        if not current_scene:
            return jsonify({"error": "无法获取当前场景"}), 500
        
        # 处理控制命令
        result = handle_command(command, source_name, visible, preferred_sources, current_scene)
        
        return jsonify(result)
        
    except Exception as e:
        logger.error(f"API调用异常: {e}")
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500


def handle_command(command: str, source_name: Optional[str], visible: bool, 
                  preferred_sources: list, current_scene: str) -> Dict[str, Any]:
    """处理具体的控制命令"""
    
    controller = obs_controller.video_controller
    
    # 如果没有指定源名称，尝试从首选源中选择
    if not source_name and preferred_sources:
        available_sources = controller.get_media_sources(current_scene)
        for preferred in preferred_sources:
            if preferred in available_sources:
                source_name = preferred
                break
    
    if command == 'sources':
        # 列出所有媒体源
        sources = controller.get_media_sources(current_scene)
        return {
            "success": True,
            "command": command,
            "current_scene": current_scene,
            "media_sources": sources,
            "preferred_sources": preferred_sources
        }
    
    elif command == 'status':
        # 获取媒体状态
        if not source_name:
            return {"error": "status命令需要指定source_name"}
        
        if not controller.check_source_exists(source_name):
            return {"error": f"媒体源不存在: {source_name}"}
        
        status = controller.get_media_status(source_name)
        return {
            "success": True,
            "command": command,
            "source_name": source_name,
            "status": status
        }
    
    elif command in ['play', 'pause', 'resume', 'stop']:
        # 播放控制命令
        if not source_name:
            return {"error": f"{command}命令需要指定source_name"}
        
        if not controller.check_source_exists(source_name):
            return {"error": f"媒体源不存在: {source_name}"}
        
        success = False
        if command == 'play':
            success = controller.play_video(source_name)
        elif command == 'pause':
            success = controller.pause_video(source_name)
        elif command == 'resume':
            success = controller.resume_video(source_name)
        elif command == 'stop':
            success = controller.stop_video(source_name)
        
        return {
            "success": success,
            "command": command,
            "source_name": source_name,
            "message": f"命令{command}{'成功' if success else '失败'}"
        }
    
    elif command in ['show', 'hide']:
        # 可见性控制
        if not source_name:
            return {"error": f"{command}命令需要指定source_name"}
        
        target_visible = (command == 'show')
        success = controller.set_video_visibility(source_name, target_visible)
        
        return {
            "success": success,
            "command": command,
            "source_name": source_name,
            "visible": target_visible,
            "message": f"{'显示' if target_visible else '隐藏'}媒体源{'成功' if success else '失败'}"
        }
    
    else:
        return {"error": f"不支持的命令: {command}"}


@app.route('/api/obs/scenes', methods=['POST'])
def get_scenes():
    """
    获取场景列表
    
    请求参数:
    {
        "host": "localhost",
        "port": 4455,
        "password": "your_password"
    }
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": "请求数据为空"}), 400
        
        host = data.get('host', 'localhost')
        port = data.get('port', 4455)
        password = data.get('password', '')
        
        # 连接到OBS
        if not obs_controller.connect_obs(host, port, password):
            return jsonify({"error": "无法连接到OBS Studio"}), 500
        
        # 获取场景列表
        scenes = obs_controller.obs_client.get_scene_list()
        current_scene = obs_controller.obs_client.get_current_scene()
        
        return jsonify({
            "success": True,
            "scenes": [scene.get('sceneName') or scene.get('scene_name', '未知') for scene in scenes] if scenes else [],
            "current_scene": current_scene
        })
        
    except Exception as e:
        logger.error(f"获取场景列表异常: {e}")
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500


@app.route('/api/obs/disconnect', methods=['POST'])
def disconnect_obs():
    """断开OBS连接"""
    try:
        obs_controller.disconnect_obs()
        return jsonify({"success": True, "message": "已断开OBS连接"})
    except Exception as e:
        logger.error(f"断开连接异常: {e}")
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500


@app.route('/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return jsonify({
        "status": "healthy",
        "service": "OBS Control API",
        "connected": obs_controller.obs_client.is_connected() if obs_controller.obs_client else False
    })


if __name__ == '__main__':
    try:
        print("🚀 启动OBS控制API服务器...")
        print("API接口:")
        print("  POST /api/obs/control - 控制OBS")
        print("  POST /api/obs/scenes - 获取场景列表")
        print("  POST /api/obs/disconnect - 断开连接")
        print("  GET  /health - 健康检查")
        print("\n服务器运行在: http://localhost:7866")
        
        app.run(host='0.0.0.0', port=7866, debug=False)
    except KeyboardInterrupt:
        print("\n🛑 服务器已停止")
        obs_controller.disconnect_obs()
    except Exception as e:
        print(f"💥 服务器启动失败: {e}")
        obs_controller.disconnect_obs()